const std = @import("std");
const c = @cImport({
    @cInclude("c_to_zig.h");
});

// 定义一个Zig函数作为C的回调
export fn zig_callback(result: c_int) void {
    std.debug.print("Callback from C received result: {d}\n", .{result});
}

// Zig函数，供C调用（在这个例子中我们不会在C中调用它，但展示了如何导出）
export fn zig_multiply(a: c_int, b: c_int) c_int {
    return a * b;
}

pub fn main() !void {
    const allocator = std.heap.page_allocator;

    // 调用C的add_numbers函数
    const sum = c.add_numbers(5, 3);
    std.debug.print("C function add_numbers(5, 3) returned: {d}\n", .{sum});

    // 调用C的get_hello_message函数
    const message = c.get_hello_message();
    std.debug.print("C function get_hello_message() returned: {s}\n", .{std.mem.span(message)});

    // 调用BusyBox风格的工具函数：count_words
    const test_string = "Hello Zig and C interoperability!";
    const word_count = c.count_words(test_string);
    std.debug.print("C function count_words() counted {d} words in '{s}'\n", .{ word_count, test_string });

    // 调用BusyBox风格的工具函数：reverse_string
    // 需要创建可修改的字符串副本
    const original_str = "Hello from Zig to C";
    const str_copy = try allocator.dupe(u8, original_str);
    defer allocator.free(str_copy);

    c.reverse_string(str_copy.ptr);
    std.debug.print("C function reverse_string() transformed '{s}' to '{s}'\n", .{ original_str, str_copy });

    // 演示C调用Zig回调函数
    std.debug.print("Calling C function with Zig callback...\n", .{});
    c.perform_operation_with_callback(7, 8, zig_callback);

    // 额外示例：将Zig字符串传递给C函数
    const zig_str = "Zig string passed to C";
    const zig_str_word_count = c.count_words(zig_str.ptr);
    std.debug.print("Zig string '{s}' has {d} words (counted by C function)\n", .{ zig_str, zig_str_word_count });
}
